<template>
  <drag-div>
    <div slot="left" class="m">
      <cm-scroll>
        <el-input
          placeholder="请输入关键词进行过滤"
          v-model="filterText"
        ></el-input>
        <el-tree
          class="filter-tree"
          :data="categoryList"
          :props="categoryProps"
          :filter-node-method="filterNode"
          ref="tree"
          node-key="id"
          :default-expanded-keys="[defaultExpandKeys]"
          :highlight-current="showTree"
          :style="maxHeight"
          @node-click="handleNodeClick"
          :expand-on-click-node="false"
          default-expand-all
        >
        </el-tree>
      </cm-scroll>
    </div>
    <div slot="right" style="padding:10px">
      <el-row>
        <box-border class="p10">
          <el-col :span="24">
            <div>
              <el-row :gutter="4">
                <el-form :inline="true" label-width="100px">
                  <el-form-item>
                    <el-input
                      placeholder="请输入关键字进行搜索"
                      v-model="searchDto.keywords"
                    ></el-input>
                  </el-form-item>

                  <el-form-item class="clear_item-margin-bottom">
                    <el-button
                      type="primary"
                      icon="el-icon-search"
                      @click="getPageData()"
                      >查询
                    </el-button>
                    <el-button
                      type="primary"
                      icon="el-icon-s-open"
                      @click="clear"
                      >重置</el-button
                    >
                    <el-button
                      type="primary"
                      icon="el-icon-circle-plus"
                      @click="newWorkForm()"
                      >新建表单
                    </el-button>
                  </el-form-item>
                </el-form>
              </el-row>
            </div>
            <div class="table_content">
              <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="全部" name="all"></el-tab-pane>
              </el-tabs>
              <page-table
                ref="multipleSelection"
                :page-data="pageData"
                :loading="loading"
                :do-get-page-data="getPageData"
              >
                <el-table-column
                  prop="name"
                  label="表单名称"
                  align="left"
                ></el-table-column>
                <el-table-column
                  label="模板上传状态"
                  align="center"
                  prop="templatesPath"
                >
                  <template slot-scope="scope">
                    <!--                    {{ scope.row.templatesPath ? "已上传" : "未上传" }}-->
                    <sz-badge
                      :value="scope.row.templatesPath ? '已上传' : '未上传'"
                      :type="statusStyle(scope.row)"
                    ></sz-badge>
                  </template>
                </el-table-column>
                <el-table-column
                  label="管理"
                  width="240"
                  align="center"
                  fixed="right"
                >
                  <template slot-scope="scope">
                    <el-tooltip placement="top" content="上传">
                      <el-button
                        type="button"
                        size="mini"
                        icon="el-icon-upload2"
                        @click="uploadWorkForm(scope.row)"
                      >
                      </el-button>
                    </el-tooltip>
                    <el-tooltip placement="top" content="编辑">
                      <el-button
                        type="button"
                        size="mini"
                        icon="el-icon-edit"
                        @click="editWorkForm(scope.row)"
                      >
                      </el-button>
                    </el-tooltip>
                    <el-tooltip placement="top" content="发布">
                      <el-button
                        type="button"
                        size="mini"
                        icon="el-icon-s-promotion"
                        @click="publishWorkForm(scope.row)"
                      >
                      </el-button>
                    </el-tooltip>
                    <el-tooltip content="删除" placement="top">
                      <el-button
                        size="mini"
                        icon="el-icon-delete"
                        @click="delWorkForm(scope.row)"
                      >
                      </el-button>
                    </el-tooltip>
                  </template>
                </el-table-column>
              </page-table>
            </div>
          </el-col>
        </box-border>
        <el-dialog
          :close-on-click-modal="false"
          @close="fail"
          width="600px"
          title="上传文件"
          :visible.sync="uploadStatus"
          ><el-upload
            accept=".doc,.docx"
            class="upload-demo"
            :action="imgHead"
            :headers="head"
            :on-success="handleSuccess"
            :on-error="handleError"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <el-button
            style="margin-top:20px;margin-left:400px"
            @click="SaveMOban"
            size="small"
            type="primary"
            >保存模板</el-button
          >
          <el-button @click="fail" size="small">取消</el-button>
        </el-dialog>
      </el-row>
    </div>
  </drag-div>
</template>
<script>
import { mapGetters } from "vuex";
import _ from "lodash";

export default {
  created() {
    this.getCategoryTree();
    this.getPageData();
  },
  data() {
    return {
      activeName: "all",
      uploadId: "",
      myUploadUrl: "",
      // 上传配置
      imgHead: window.api.uploadUrl1 + "?path=workflow/form/template",
      head: {
        userRole: "ADMIN",
        token: window.sessionStorage.getItem("token")
      },
      fileList: [], //el-upload默认
      uploadStatus: false,
      categoryList: [],
      filterText: "",
      categoryProps: {
        label: "name",
        value: "id",
        children: "children"
      },
      searchDto: {
        categoryId: "",
        pageSize: 10,
        pageIndex: "",
        keywords: ""
      },
      loading: false,
      defaultExpandKeys: "",
      showTree: false,
      pageData: {}
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  computed: {
    ...mapGetters({}),
    maxHeight() {
      return { height: this.clientHeight - 220 + "px" };
    }
  },
  methods: {
    // 状态颜色设置
    statusStyle(row) {
      let cls = "";
      if (row.templatesPath) {
        cls = "success";
      } else {
        cls = "warning";
      }
      return cls;
    },
    handleClick(tab, event) {
      let status = "all";
      switch (tab.paneName) {
        case "all":
          status = "all";
          break;
      }
    },
    // 获取表单类型
    getCategoryTree() {
      this.API.getCategoryTree({ type: "FORM", parentId: 0 }).then(res => {
        this.categoryList = [];
        if (res.data) {
          this.categoryList.push({ name: "全部", id: "", children: res.data });
        }
      });
    },
    // 工作表单分页列表
    getPageData(val) {
      if (this.searchDto.categoryId && this.searchDto.categoryId.length > 0) {
        this.searchDto.categoryId = this.searchDto.categoryId[0];
      }
      let tem = Object.assign(this.searchDto, val);
      this.API.getWorkflowFormPageList(tem).then(res => {
        this.pageData = res.data;
      });
    },
    //数据表单删除
    delWorkForm(row) {
      this.$confirm("确认删除当前表单?", "提示", {})
        .then(() => {
          let tem = {
            id: row.id
          };
          this.API.deleteWorkflowFormById(tem).then(res => {
            this.success("删除成功");
            this.getPageData();
          });
        })
        .catch(() => {});
    },
    // 编辑表单
    editWorkForm(row) {
      let data = "/formDesign.html#/?operate=update&formId=" + row.id;
      window.open(data, "_blank");
    },
    // 发布表单
    publishWorkForm(row) {
      this.$confirm("确认发布当前表单?", "提示", {})
        .then(() => {
          if (row.id) {
            this.API.publishWorkflowFormById({ id: row.id }).then(res => {
              this.success("发布表单成功!");
            });
          }
        })
        .catch(() => {});
    },
    // 新建表单
    newWorkForm() {
      let data = "/formDesign.html#/?operate=create";
      window.open(data, "_blank");
    },
    //上传
    uploadWorkForm(row) {
      console.log(row);
      this.uploadStatus = true;
      this.uploadId = row.id;
      if (row.templatesPath) {
        this.fileList.push({
          name: row.templatesPath.split("/")[3],
          response: { value: row.templatesPath }
        });
      }
    },
    clear() {
      this.searchDto = {
        categoryId: "",
        pageSize: 10,
        keywords: ""
      };
      this.getPageData();
    },
    //上传成功
    handleSuccess(res, file, fileList) {
      this.myUploadUrl = fileList[0].response.value;
    },
    handleError(err, file, fileList) {
      this.$notify.error({
        title: "错误",
        dangerouslyUseHTMLString: true,
        duration: 2000,
        message: `<p style="display: block;width: 260px; word-wrap: break-word">${
          JSON.parse(err.message).message
        }</p>`
      });
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      this.openTabPage(
        window.api.preFile +
          "?url=" +
          window.api.image +
          "/" +
          file.response.value +
          "?token=" +
          window.sessionStorage.getItem("token")
      );
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    SaveMOban() {
      let tem = {
        id: this.uploadId,
        templatesPath: this.myUploadUrl
      };
      this.API.saveWorkflowFormTemplates({ body: tem }).then(ret => {
        this.success("保存成功");
        this.uploadStatus = false;
        this.getPageData();
      });
    },
    fail() {
      this.uploadStatus = false;
      this.fileList = [];
    },
    // 过滤分类
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    // 左侧分类树的单击事件
    handleNodeClick(val) {
      this.searchDto = {
        categoryId: "",
        pageSize: 10,
        pageIndex: "",
        keywords: ""
      };
      this.searchDto.categoryId = val.id;
      this.getPageData();
    }
  }
};
</script>
<style scoped lang="less"></style>
